package com.lxz.datasource.config.druid;


import com.lxz.datasource.constant.ServiceMethodPrefix;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;

@Aspect
@Configuration
public class TransactionAdviceConfig {

	@Value("${db.openSlave:false}")
	private boolean openSlave; 
	
	@Autowired
	private PlatformTransactionManager transactionManager;

	public DBTransactionInterceptor txAdvice() {

		DefaultTransactionAttribute txAttr_REQUIRED = new DefaultTransactionAttribute();
		txAttr_REQUIRED.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

		DefaultTransactionAttribute txAttr_REQUIRED_READONLY = new DefaultTransactionAttribute();
		txAttr_REQUIRED_READONLY.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		txAttr_REQUIRED_READONLY.setReadOnly(true);
		NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
		// 增删改
		for (String notQueryMethodPrefix : ServiceMethodPrefix.NOT_QUERY_PREFIX) {
			source.addTransactionalMethod(notQueryMethodPrefix + "*", txAttr_REQUIRED);
		}
		// 查
		for (String queryMethodPrefix : ServiceMethodPrefix.QUERY_PREFIX) {
			source.addTransactionalMethod(queryMethodPrefix + "*", txAttr_REQUIRED_READONLY);
		}
		// 其余
		source.addTransactionalMethod("*", txAttr_REQUIRED_READONLY);
		
		return new DBTransactionInterceptor(transactionManager, source, openSlave);
	}

	@Bean
	public Advisor txAdviceAdvisor() {
		AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
		pointcut.setExpression(DBTransactionInterceptor.AOP_POINTCUT_EXPRESSION);
		return new DefaultPointcutAdvisor(pointcut, txAdvice());
	}
}
